﻿using Autofac;
using Autofac.Configuration;
using SocialCee.Configuration.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SocialCee.Configuration
{
    /// <summary>
    /// Read configuration
    /// </summary>
    public class Reader
    {
        #region Properties
        private static Config value;
        /// <summary>
        /// Lazy Loader for config object
        /// </summary>
        public static Config Value
        {
            get
            {
                if (value == null)
                    Read();

                return value;
            }
        }
        #endregion

        /// <summary>
        /// Reads all configuration objects from 'Configs' directory
        /// </summary>
        private static void Read()
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));

            DirectoryInfo di = new DirectoryInfo(".\\Configs");
            FileInfo[] fileConfigs = di.GetFiles("*.config");
            if (fileConfigs.Length > 0)
            {
                foreach (FileInfo fi in fileConfigs)
                {
                    builder.RegisterModule(new XmlFileReader(fi.FullName));
                }
            }

            using (var container = builder.Build())
            {
                if (container.IsRegistered(typeof(Config)))
                {
                    value = container.Resolve<Config>();
                }
            }
        }
    }
}
